package com.mixi.feedreader;

import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.Inflater;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;

import com.mixi.feedreader.FeedCollection.Feed;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.FeatureInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.RemoteViews.ActionException;
import android.widget.Toast;

public class FeedReaderActivity extends Activity {
    /** Called when the activity is first created. */
	public static final String tag = "mixi";
	public static int cnt = 0;
	public static int current = 0;
	public static ArrayList<Holder> hList;
	public String currentLink ="";
	
	private FeedCollection feedCollection;
	private ImageButton publisherBtn;
	private ListView lsx;
	
<<<<<<< .mine
	
=======
	private ImageButton publisherBtn;
	
>>>>>>> .r6
	//private Adapter currentAdaper
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 101)
			if(resultCode == RESULT_OK){
				//if(data!=null)
				Toast.makeText(FeedReaderActivity.this
						, "Select "+data.getExtras().getString("code")
						, Toast.LENGTH_SHORT).show();
				setCategoryList(Integer.parseInt(data.getExtras().getString("code")));
				
			}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 101)
			if(resultCode == RESULT_OK){
				if(data!=null)
				Toast.makeText(FeedReaderActivity.this
						, "Select "+data.getExtras().getString("code")
						, Toast.LENGTH_SHORT).show();
			}
	}
	
<<<<<<< .mine
	private void setCategoryList(int index){
		
		if(index>feedCollection.getList().size())return;
		
		Feed fx = feedCollection.getList().get(index-1);
		
		
		Log.i(tag, "\n=========== Change publisher =============\n");
    	Log.i(tag, fx.getId()+"");
    	Log.i(tag, fx.getPublisher());
    	
    	for(String lnk: fx.getCateURL() ){
    		String word[] = lnk.split("\\|");  
    		Log.i(tag, word[0]+" :: "+word[1]);
    		currentLink = lnk;
        }
	}
	
	
	
	
=======
	
	
	
>>>>>>> .r6
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
<<<<<<< .mine
=======
      

        ListView lsx = (ListView) findViewById(R.id.listView1);//= new ListView(this);
>>>>>>> .r6
        publisherBtn = (ImageButton)findViewById(R.id.publisher_btn);
        publisherBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				Intent callPublisher = new Intent(FeedReaderActivity.this,Publisher.class);
				startActivityForResult(callPublisher, 101);// Assume 101 as publisherCall code
			}
		});
        
<<<<<<< .mine
        //--- Test Feed
        feedCollection = new FeedCollection();
        ArrayList<Feed> fx = feedCollection.getList();
        for(Feed fn:fx){
        	Log.i(tag, "\n====================================\n");
        	Log.i(tag, fn.getId()+"");
        	Log.i(tag, fn.getPublisher());
        	
        	for(String lnk: fn.getCateURL() ){
        		String word[] = lnk.split("\\|");  
        		Log.i(tag, word[0]+" :: "+word[1]);
            }
        	
        }
        
        
        
        
        
        

        lsx = (ListView) findViewById(R.id.listView1);//= new ListView(this);
        publisherBtn = (ImageButton)findViewById(R.id.publisher_btn);
        publisherBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				Intent callPublisher = new Intent(FeedReaderActivity.this,Publisher.class);
				startActivityForResult(callPublisher, 101);// Assume 101 as publisherCall code
			}
		});
        
       
        
=======
        
        
        
        
        
        
        
        
>>>>>>> .r6
        try{
        	
//			String word[] = lnk.split("\\|");  
//    		Log.i(tag, word[0]+" :: "+word[1]);
			
        	hList = new ArrayList<Holder>();
        	URL feed = new URL("http://www.voanews.com/templates/Articles.rss?sectionPath=/thai/news/economy-business");
//        	URL feed = new URL(word[1]);
        	SAXParserFactory spf = SAXParserFactory.newInstance();
        	SAXParser sp = spf.newSAXParser();
        	
        	XMLReader xr = sp.getXMLReader();
        	TagHandler th = new TagHandler();
        	xr.setContentHandler(th);
        	
        	xr.parse(new InputSource(feed.openStream()));
        	ParsedTag ptlist = th.getParseTag();
        	
        	
        	ptlist.getExtractedString();
//        	tx.setText(ptlist.getExtractedString());
        	
        	String test ="";
        	for(Holder item : hList){
        		String temp = item.getTitle()+"\n";
        		temp+=item.getLink()+"\n";
        		temp+=item.getDescription()+"\n";
        		temp+="===========\n";
        		test+=temp;
        	}
        	//tx.setText(test+"x");
        	
        	
        	
        }catch (Exception e) {
			// TODO: handle exception
        	Log.i(tag, " :: "+e.getMessage());
        	e.printStackTrace();
		}
        
        //setContentView(tx);
        lsx.setAdapter(new NewsAdapter(this,hList));
        
        
//        setCategoryList(1);
//        refreshCurrentList(lsx,currentLink);
        
    }


//	private void refreshCurrentList(ListView lsx,String lnk) {
//		
//	}
    
    
    
    
    
    
    
    
    
    
    
    
    
    public class NewsAdapter extends BaseAdapter{

    	ArrayList<Holder> currentList;
    	Context parentContext;
    	LayoutInflater inflater;
    	
    	
    	public NewsAdapter(Context context,ArrayList<Holder> list){
    		currentList = list;
    		Log.i(FeedReaderActivity.tag,"News Adapter constructed "+list.size());
    		parentContext = context;
    		//inflater = (LayoutInflater) parentContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    		inflater = (LayoutInflater) parentContext.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    	}
    	
		public int getCount() {
			Log.i(FeedReaderActivity.tag, "call getCout"+currentList.size());
			return currentList.size();
		}

		public Object getItem(int position) {
			return currentList.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			Log.i(FeedReaderActivity.tag, "call getView");
			ItemHolder item;
			final int pos = position;
			if(convertView == null){
				convertView = inflater.inflate(R.layout.list_item, null, false);
				item = new ItemHolder();
				item.title = (TextView) convertView.findViewById(R.id.title_tx);
				item.description = (TextView) convertView.findViewById(R.id.description_tx);
				item.link = (ImageButton) convertView.findViewById(R.id.link_btn);
				
				convertView.setTag(item);
			}else{
				item = (ItemHolder) convertView.getTag();
			}
			
			item.title.setText(((Holder)this.getItem(position)).title);
			item.description.setText(((Holder)this.getItem(position)).description);
			item.link.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					startIntentForId(pos);
				}
			});
			
			Log.i(FeedReaderActivity.tag, " Assemble "+position);
			return convertView;
		}
		
		
		private void startIntentForId(int id){
			String url = ((Holder)this.getItem(id)).link;
			Log.i(FeedReaderActivity.tag, "Click on"+url);
			
			Intent ix = new Intent(Intent.ACTION_VIEW);
			ix.setData(Uri.parse(url));
			startActivity(ix);
			
		}
		
		public class ItemHolder{
	    	public TextView title;
	    	public TextView description;
	    	public ImageButton link;
	    }
    	
    }
    
    
}